
package com.dog.basics.service.wishwash.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.dog.basics.bean.model.common.DogConnectFlowing;
import com.dog.basics.bean.model.wishwash.*;
import com.dog.basics.common.constant.CommonConstants;
import com.dog.basics.common.util.OrderCodeFactory;
import com.dog.basics.common.util.SpringContextUtils;
import com.dog.basics.dao.common.DogConnectFlowingMapper;
import com.dog.basics.dao.wishwash.DogHxDevMapper;
import com.dog.basics.dao.wishwash.DogHxDevNodeMapper;
import com.dog.basics.dao.wishwash.DogHxFieldMapper;
import com.dog.basics.bean.dto.api.wishwash.ApiDogHxOrderAddDto;

import java.math.BigDecimal;
import java.util.List;
import java.util.Set;

import com.dog.basics.service.common.DogUserConnectService;
import com.dog.basics.service.wishwash.DogHxOrderItmeService;
import lombok.extern.log4j.Log4j2;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dog.basics.dao.wishwash.DogHxOrderMapper;
import com.dog.basics.service.wishwash.DogHxOrderService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 订单信息
 *
 * @author cy code generator
 * @date 2021-07-09 17:40:27
 */
@Log4j2
@Service
@AllArgsConstructor
public class DogHxOrderServiceImpl extends ServiceImpl<DogHxOrderMapper, DogHxOrder> implements DogHxOrderService {

    private final DogHxDevNodeMapper devNodeMapper;
    private final DogHxDevMapper devMapper;
    private final DogConnectFlowingMapper flowingMapper;
    private final DogHxFieldMapper fieldMapper;

    /**
     * @Description: 增加APP
     * @Param: obj
     * @return: Boolean
     * @author cy code generator
     * @date 2021-07-09 17:40:27
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveApiObj(ApiDogHxOrderAddDto obj) {
        // API - 数据信息转换
        DogHxOrder apiObjAdd = BeanUtil.toBean(obj, DogHxOrder.class);
        // 判断 -子订单信息
        //Validator.validateTrue(CollUtil.isNotEmpty(obj.getOrderItmeAddDtos()), "order.itme.no.null");
        if (CollUtil.isEmpty(obj.getOrderItmeAddDtos())) {
            return Boolean.TRUE;
        }
        // 声明自类实体接收
        Set<Long> set = CollUtil.newHashSet();
        List<DogHxOrderItme> orderItmes = CollUtil.newArrayList();
        for (int i = 0; i < obj.getOrderItmeAddDtos().size(); i++) {
            // 转化设备信息
            DogHxOrderItme orderItme = BeanUtil.toBean(obj.getOrderItmeAddDtos().get(i), DogHxOrderItme.class);
            // 判断子设备是否存在
            DogHxDevNode hxDevNode = devNodeMapper.selectById(orderItme.getDevNodeId());
            Validator.validateNotNull(hxDevNode, "dev.itme.data.null");
            orderItme.setNodeType(hxDevNode.getNodeType());
            // 查询设备信息是否存在
            DogHxDev hxDev = devMapper.selectById(orderItme.getDevId());
            Validator.validateEqual(hxDevNode.getDevId(), hxDev.getId(), "dev.item.dev.error");
            // 保存场地信息
            set.add(hxDev.getFieldId());
            // 子设备信息 [暂时不用]
            // orderItme.setOrderItmePrice(NumberUtil.mul(orderItme.getDevUnitPrice(), orderItme.getOrderQuantity()));
            // 使用总价和单价计算个数
            BigDecimal div = NumberUtil.div(orderItme.getOrderItmePrice(), orderItme.getDevUnitPrice());
            orderItme.setOrderQuantity(div.intValue());
            // 判断金额
            Validator.validateTrue(NumberUtil.isGreater(orderItme.getOrderItmePrice(), BigDecimal.ZERO), "order.iteme.price.min");
            orderItmes.add(orderItme);
            // 计算总价格
            apiObjAdd.setOrderMoney(NumberUtil.add(apiObjAdd.getOrderMoney(), orderItme.getOrderItmePrice()));
        }
        // 判断场地标识是否两个
        Validator.validateTrue(set.size() <= 1, "order.field.max.tow");
        // 数据信息补充
        apiObjAdd.setPayState(1);
        apiObjAdd.setCreateTime(DateUtil.currentSeconds());
        apiObjAdd.setCreateBy(0L);
        apiObjAdd.setFieldId(set.iterator().next());
        // 查询场地信息
        DogHxField hxField = fieldMapper.selectById(apiObjAdd.getFieldId());
        apiObjAdd.setFieldUserId(hxField.getFieldUserId());
        apiObjAdd.setAgentUserId(hxField.getFieldAgentId());
        // 执行添加数据信息
        Validator.validateTrue(this.save(apiObjAdd), "common.save");
        // 循环处理主订单标识
        for (int i = 0; i < orderItmes.size(); i++) {
            orderItmes.get(i).setOrderId(apiObjAdd.getId());
            orderItmes.get(i).setCreateTime(DateUtil.currentSeconds());
            orderItmes.get(i).setCreateBy(0L);
        }
        // 添加子订单信息
        boolean b = SpringContextUtils.getBean(DogHxOrderItmeService.class).saveBatch(orderItmes);
        Validator.validateTrue(b, "order.add.item.error");
        // 处理 - 订单流水
        DogConnectFlowing flowing = new DogConnectFlowing();
        flowing.setUserId(obj.getOrderItmeAddDtos().get(0).getDevId());
        flowing.setFlowSerialNo(OrderCodeFactory.getWaterCode(flowing.getUserId()));
        flowing.setFlowMoney(apiObjAdd.getOrderMoney());
        flowing.setFlowAfterOperationMoney(BigDecimal.ZERO);
        flowing.setFlowBeforeOperationMoney(BigDecimal.ZERO);
        flowing.setFlowType(0);
        flowing.setFromType(0);
        flowing.setType(1);
        flowing.setObjId(apiObjAdd.getId());
        flowing.setFlowExplain("Laundry and drying order revenue");
        flowing.setCreateBy(flowing.getUserId());
        flowing.setCreateTime(DateUtil.currentSeconds());
        Validator.validateTrue(SqlHelper.retBool(flowingMapper.insert(flowing)), "flowing.water.error");
        // 判断分润信息
        if (CollUtil.isNotEmpty(set)) {
            if (ObjectUtil.isNotNull(hxField)) {
                // 处理订单分润信息
                //      1-添加代理商收益
                if (!Validator.equal(hxField.getFieldAgentId(), CommonConstants.DEFAULT_VAL_LONG)) {
                    // 计算收益金额
                    BigDecimal agentMone = NumberUtil.mul(apiObjAdd.getOrderMoney(), hxField.getFieldAgentProfitSharingRatio());
                    // 判断收益是否大于 0
                    if (NumberUtil.isGreater(agentMone, BigDecimal.ZERO)) {
                        // 增添流水
                        DogConnectFlowing agentFlowing = new DogConnectFlowing();
                        agentFlowing.setUserId(hxField.getFieldAgentId());
                        agentFlowing.setFlowSerialNo(flowing.getFlowSerialNo());
                        agentFlowing.setFlowMoney(agentMone);
                        agentFlowing.setFlowType(0);
                        agentFlowing.setFromType(1);
                        agentFlowing.setType(1);
                        agentFlowing.setObjId(apiObjAdd.getId());
                        agentFlowing.setFlowExplain("Order sharing");
                        // 金额账户操作
                        SpringContextUtils.getBean(DogUserConnectService.class).addUserConnect(agentFlowing.getUserId(), agentFlowing.getFlowMoney(), agentFlowing);
                    }
                }
                //      2-添加场地人收益
                if (!Validator.equal(hxField.getFieldUserId(), CommonConstants.DEFAULT_VAL_LONG)) {
                    // 计算收益金额
                    BigDecimal fieldMone = NumberUtil.mul(apiObjAdd.getOrderMoney(), hxField.getFieldLocalProfitSharingRatio());
                    // 判断收益是否大于 0
                    if (NumberUtil.isGreater(fieldMone, BigDecimal.ZERO)) {
                        // 增添流水
                        DogConnectFlowing fieldFlowing = new DogConnectFlowing();
                        fieldFlowing.setUserId(hxField.getFieldUserId());
                        fieldFlowing.setFlowSerialNo(flowing.getFlowSerialNo());
                        fieldFlowing.setFlowMoney(fieldMone);
                        fieldFlowing.setFlowType(0);
                        fieldFlowing.setFromType(1);
                        fieldFlowing.setType(1);
                        fieldFlowing.setObjId(apiObjAdd.getId());
                        fieldFlowing.setFlowExplain("Order sharing");
                        // 金额账户操作
                        SpringContextUtils.getBean(DogUserConnectService.class).addUserConnect(fieldFlowing.getUserId(), fieldFlowing.getFlowMoney(), fieldFlowing);
                    }
                }
            } else {
                log.error("场地信息不存在:{},订单号:{}", set.iterator().next(), apiObjAdd.getId());
            }
        }
        return Boolean.TRUE;
    }

}
